/*
 * Copyright 2009 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.gtugs;

import com.google.appengine.api.memcache.MemcacheService;
import com.google.appengine.api.memcache.MemcacheServiceFactory;

import org.gtugs.domain.Chapter;
import org.gtugs.domain.Point;
import org.gtugs.repository.PMF;
import org.gtugs.service.GoogleMapsService;

import java.io.IOException;

import javax.jdo.PersistenceManager;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@SuppressWarnings("serial")
public class GeocodeServlet extends HttpServlet {

  private GoogleMapsService mapsService = new GoogleMapsService("ABQIAAAAVcC1CwycXgD607vgA6-JWRQsQrdbh9VYytIyhTexABq-UD140xRDqWhEuEAiRVhjGXFCXv8ybo6Mfw");

  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws IOException {
    response.setContentType("text/plain");
    MemcacheService ms = MemcacheServiceFactory.getMemcacheService();
    ms.clearAll();

    String chapterId = request.getParameter("id");
    Chapter chapter = retrieveChapter(chapterId);

    if (chapter == null) {
      response.getWriter().println("Geocode update failed: chapter not found");
      return;
    }

    response.getWriter().println(chapter.getName());

    Point point = mapsService.getCoordinates(chapter.getCity(),
        chapter.getState(), chapter.getCountry());
    if (point == null) {
      response.getWriter().println("Geocode update failed: point not found");
      return;
    } else {
      chapter.setLatitude(point.getLatitude());
      chapter.setLongitude(point.getLongitude());

      PersistenceManager pm = PMF.get().getPersistenceManager();
      try {
        pm.makePersistent(chapter);
      } catch (Exception e) {
        response.getWriter().println("Geocode update failed: JDO error");
        return;
      } finally {
        pm.close();
      }
    }

    chapter = null;
    chapter = retrieveChapter(chapterId);

    if (chapter == null) {
      response.getWriter().println("Geocode update failed: chapter not found");
      return;
    }

    response.getWriter().println("Geocode update succeeded");
    response.getWriter().println(point.getLatitude() + ", " + point.getLongitude());
    response.getWriter().println(chapter.getLatitude() + ", " + chapter.getLongitude());
  }

  private Chapter retrieveChapter(String idString) {
    Long id = null;

    try {
      id = Long.parseLong(idString);
    } catch (NumberFormatException ex) {
      return null;
    }

    PersistenceManager pm = PMF.get().getPersistenceManager();
    try {
      return (Chapter) pm.getObjectById(Chapter.class, id);
    } finally {
      pm.close();
    }
  }
}
